//
//  LBPayVC.m
//  V-Learn
//
//  Created by Apple on 2019/1/1.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "LBPayVC.h"
#import "FZXPayCell.h"
#import "WXApi.h"

#import "LBCardQuanVC.h"

#import "LBWechatPayRequestModel.h"
#import "VKVoucherController.h"

#import "LBPaySuccessVC.h"
#import "LBPayFaileVC.h"
#import "WKShuangyuSuccessViewController.h"
#define defaultTag 2019
@interface LBPayVC ()<UITableViewDelegate,UITableViewDataSource,LBCardQuanVCDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger btnTag;//默认选中的Tag
@property (nonatomic, assign) BOOL isYueOrZhifubao;//优惠券
@property (nonatomic, strong) NSString *payType;//支付类型 1  支付宝  2 微信
@property (nonatomic, strong) NSString *quanhouPrice;//优惠后的价格
@property (nonatomic, strong) LBCardquanModel *cardquanModel;
@property (nonatomic, strong) UILabel *selectLab;
@property (nonatomic, assign) BOOL isSuccessSelect;
@property (nonatomic, strong) UILabel *nameLab;/**课程名称*/
@property (nonatomic, strong) UILabel *priceLab;/**价格*/
@property (nonatomic, strong) NSString *moneyString;
@end

@implementation LBPayVC
- (UILabel *)nameLab{
    if (!_nameLab) {
        _nameLab = [UILabel labelWithText:@"" andTextColor:nil andName:nil andFontSize:15*kScaleFit];
    }
    return _nameLab;
}
- (UILabel *)priceLab{
    if (!_priceLab) {
        _priceLab = [UILabel labelWithText:@"" andTextColor:nil andName:nil andFontSize:15*kScaleFit];
    }
    return _priceLab;
}
- (UILabel *)selectLab{
    if (!_selectLab) {
        _selectLab = [UILabel labelWithText:@"请选择" andTextColor:rgb(101,101,101) andName:nil andFontSize:15];
    }
    return _selectLab;
}
- (void)setupFengexian{
    //设置tableView 分割线不到边
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"兑换";
    self.btnTag = defaultTag+0;
    //区分是支付宝支付  还是 余额 支付
    self.isYueOrZhifubao = YES;
    
    self.isSuccessSelect = NO;
    [self setupUI];
    [self setupFengexian];
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setupUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.backgroundColor = rgb(242,242,242);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    UIView *footerView = [UIView new];
    footerView.backgroundColor = rgb(242,242,242);
    //底部视图
    self.tableView.tableFooterView = footerView;
    footerView.frame = CGRectMake(0, 0, ScreenW, 300);
//    footerView.backgroundColor = [UIColor redColor];
    
    [self.view addSubview:self.tableView];
    
    
    UILabel *firstLab = [UILabel labelWithText:@"・你在该iOS设备进行虚拟币充值及消费;" andTextColor:rgb(102, 102, 102) andName:nil andFontSize:12];
    [footerView addSubview:firstLab];
    [firstLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(0);
    }];
    
    UILabel *secodLab = [UILabel labelWithText:@"・充值余额仅限iOS系统消费，无法在其他系统使用;" andTextColor:rgb(102, 102, 102) andName:nil andFontSize:12];
    [footerView addSubview:secodLab];
    [secodLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(firstLab.mas_bottom).mas_equalTo(5);
        make.left.mas_equalTo(15);
    }];
    
    UILabel *thirdLab = [UILabel labelWithText:@"・充值余额和消费不可转让、退换和申请发票!" andTextColor:rgb(102, 102, 102) andName:nil andFontSize:12];
    [footerView addSubview:thirdLab];
    [thirdLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(secodLab.mas_bottom).mas_equalTo(5);
        make.left.mas_equalTo(15);
    }];
    UIButton *payButton = [[UIButton alloc] init];
    [self.view addSubview:payButton];
    payButton.layer.cornerRadius = 22;
    payButton.layer.masksToBounds = YES;
    [payButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(-50);
    }];
    [payButton setTitle:@"确认兑换" forState:UIControlStateNormal];
    [payButton setTitleColor:rgb(255,255,255) forState:UIControlStateNormal];
    payButton.titleLabel.font = LBFont(18);
//    payButton.backgroundColor = rgb(233,84,18);
    [payButton setBackgroundImage:LBImage(@"wk_pay_button") forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(clickzhiFuBtn:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"支付结果" style:UIBarButtonItemStyleDone target:self action:@selector(clickPayBtn:)];
}
- (void)clickPayBtn:(UIButton *)sender{
    LBPayFaileVC *paySuccessVC = [LBPayFaileVC new];
    [self.navigationController pushViewController:paySuccessVC animated:YES];
}
- (void)clickzhiFuBtn:(UIButton *)sender{
//    NSLog(@"去支付");

    [self dealWithOrderPay];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getGold];
}
- (void)getGold{
    [WYHXNetWorkManager post:WKCheckMoney_WKURL params:@{@"token":[UserModel getUserModel].token} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            NSLog(@"%@",responseObj);
            
            //保存余额
            NSString *string = [NSString stringWithFormat:@"%@",responseObj[@"data"][@"userMoney"]];
            self.moneyString = string;
        }
        [self.tableView reloadData];
    }];
}

// 发起支付请求
- (void)dealWithOrderPay {
    // 业务逻辑，先向服务器发起预支付请求，服务器返回支持订单信息。
    // ...
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;

    BOOL isGD;
    NSString *courseType;
    if ([self.type isEqualToString:@"2"]) {
        isGD = YES;
        courseType = @"2";//self.packModel.data.
    }else{
        isGD = NO;
        courseType = self.type;//self.model.courseType;
    }
    NSString *courseId = self.courserId;//isGD?self.packModel.data.packId:self.model.courseId;
    NSString *courseName =self.name;//isGD?self.packModel.data.packName:self.model.courseName;
    NSString *coursePrice =self.price;//isGD?self.packModel.data.packagePrice: self.model.coursePrice;//课程价格

    NSString *payPrice;
    //如果是回调优惠券价格
    if (self.isSuccessSelect) {
        payPrice = self.quanhouPrice;
        
    }
    if (payPrice.length==0||payPrice==nil) {
        payPrice = coursePrice;
    }
    NSString *voucherId;
    if (self.cardquanModel.voucherId.length>0) {
        voucherId = self.cardquanModel.voucherId;//代金券id
    }else{
        voucherId = @"";
    }
    
    [data setObject:token forKey:@"token"];
    [data setObject:courseId forKey:@"courseId"];
    [data setObject:courseName forKey:@"courseName"];
    [data setObject:coursePrice forKey:@"coursePrice"];
    if (payPrice.length==0) {
        
    }
    [data setObject:payPrice forKey:@"payPrice"];
    [data setObject:voucherId forKey:@"voucherId"];//代金券ID

    [data setObject:courseType forKey:@"courseType"];//1 课程 2 课程包

    //WKWechatPay_WKURL
    //乐学币  WKCoursePay_WKURL
    NSString *userMoney = self.moneyString;//[[NSUserDefaults standardUserDefaults] objectForKey:@"userMoney"];
    //判断当前用户余额是否大于当前课程价格  小于 去充值
    if ([userMoney integerValue]<[payPrice integerValue]) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"余额不足" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"去充值" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //这里来个弹框是否去充值
            MoneyViewController *moneyVC = [[MoneyViewController alloc] init];
            [self.navigationController pushViewController:moneyVC animated:YES];

        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"网课不退费，谨慎购买" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [WYHXNetWorkManager post:WKCourseRecharge_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
                //        NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];

                if ([code integerValue]==200) {
                    if ([self.jumpType isEqualToString:@"6"]) {
                        //返回指定控制器，双语工程申请控制器
                        for (UIViewController *controller in self.navigationController.viewControllers) {
                            if ([controller isKindOfClass:[WKShuangyuSuccessViewController class]]) {
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                    }else{
                        LBPaySuccessVC *paySuccessVC = [[LBPaySuccessVC alloc] init];
                        paySuccessVC.type = self.type;
                        [self.navigationController pushViewController:paySuccessVC animated:YES];
                    }
                }else if ([code integerValue]==501){
                    NSString *msg = responseObj[@"msg"];
                    [MBProgressHUD showSuccess:msg toView:self.view];
//                    return ;
                    if ([self.jumpType isEqualToString:@"6"]) {
                        //返回指定控制器，双语工程申请控制器
                        for (UIViewController *controller in self.navigationController.viewControllers) {
                            if ([controller isKindOfClass:[WKShuangyuSuccessViewController class]]) {
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                    }else{
                        LBPaySuccessVC *paySuccessVC = [[LBPaySuccessVC alloc] init];
                        paySuccessVC.type = self.type;
                        paySuccessVC.addInfo = msg;
                        paySuccessVC.addType = @"1";
                        [self.navigationController pushViewController:paySuccessVC animated:YES];
                    }
                }else{
                    LBPayFaileVC *paySuccessVC = [[LBPayFaileVC alloc] init];
                    [self.navigationController pushViewController:paySuccessVC animated:YES];
                }
            }];
            
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
        

    }
    

        
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section==0) {


        if (indexPath.row==0) {
            cell.textLabel.text = @"名称";
            cell.textLabel.textColor = rgb(51,51,51);
            
            [cell.contentView addSubview:self.nameLab];
            [self.nameLab makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-15*kScaleFit);
                make.centerY.mas_equalTo(cell.contentView);
            }];
            self.nameLab.text = self.name;
            self.nameLab.textColor = rgb(101,101,101);
            
        }
        if (indexPath.row==1) {
            cell.textLabel.text = @"价格";
            cell.textLabel.textColor = rgb(51,51,51);
            [cell.contentView addSubview:self.priceLab];
            
            [self.priceLab makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-15*kScaleFit);
                make.centerY.mas_equalTo(cell.contentView);
            }];
            self.priceLab.text = self.price;
            self.priceLab.textColor = rgb(233,38,18);
        }
        if (indexPath.row==2) {
            cell.textLabel.text = @"优惠券";
            cell.textLabel.textColor = rgb(51,51,51);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            [cell.contentView addSubview:self.selectLab];
            [self.selectLab remakeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(0*kScaleFit);
                make.centerY.mas_equalTo(cell.contentView);
            }];
            
            if (self.isSuccessSelect) {
                self.selectLab .text = [NSString stringWithFormat:@"优惠券减%@",self.cardquanModel.voucherPrice];
            }else{
                self.selectLab .text = @"请选择";
            }
            self.selectLab .textColor = rgb(101,101,101);
        }
        cell.textLabel.font = LBFont(15*kScaleFit);
        return cell;

    }

    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section==0) {
        UIView *headerView = [UIView new];

        
        UILabel *payTypeLab = [UILabel labelWithText:@"¥29" andTextColor:rgb(233,38,18) andName:nil andFontSize:18*kScaleFit];
        [headerView addSubview:payTypeLab];
        [payTypeLab makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15*kScaleFit);
            make.centerY.mas_equalTo(headerView);
        }];
        headerView.backgroundColor = rgb(242,242,242);

        if (self.isSuccessSelect) {
            payTypeLab.text = self.quanhouPrice;
        }else{
            payTypeLab.text = self.price;
        }
        
        UILabel *payTypeLab2 = [UILabel labelWithText:@"合计:" andTextColor:rgb(233,38,18) andName:nil andFontSize:12*kScaleFit];
        [headerView addSubview:payTypeLab2];
        [payTypeLab2 makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(payTypeLab.mas_left).mas_equalTo(-10*kScaleFit);
            make.centerY.mas_equalTo(headerView);
        }];
        headerView.backgroundColor = rgb(242,242,242);
        return headerView;
    }else{
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 40;
    }else{
        return 0;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (indexPath.row==2) {
            //暂时屏蔽
//            [MBProgressHUD showSuccess:@"该功能暂未开放" toView:self.view];
//            return;
            
            LBCardQuanVC *quanVC = [[LBCardQuanVC alloc] init];
            quanVC.delegate = self;
            quanVC.courseId = self.courserId;//self.model.courseId;
            quanVC.type = self.type;
            [self.navigationController pushViewController:quanVC animated:YES];
        }
    }
}
#pragma mark - LBCardQuanVCDelete
- (void)clickLBCardQuanVCCardQuandidselect:(LBCardquanModel *)cardquanModel :(NSString *)type isUse:(BOOL)isUse{
//    NSLog(@"请教数据，拿到代金券后请求后台接口数据，展示最终价格");
    
#warning TODO
    if (isUse) {
        NSString *price;
        price = self.price;
        NSString *price2 = cardquanModel.voucherPrice;
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:price forKey:@"coursePrice"];
        [data setObject:price2 forKey:@"voucherPrice"];
        self.cardquanModel = cardquanModel;
        [WYHXNetWorkManager post:WKCardCalculation_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
//                NSLog(@"%@",responseObj);
                NSString *data = responseObj[@"data"];
                if (data) {
                    //                self.type = @"1";
                    self.isSuccessSelect = YES;
                    self.quanhouPrice = [NSString stringWithFormat:@"%@",data];
                    
                }
            }
            [self.tableView reloadData];
        }];
        
    }else{

        self.isSuccessSelect = NO;
        [self.tableView reloadData];
    }
    
}
@end
